import {
	createRouter,
	createWebHistory,
	type RouteRecordRaw,
	type NavigationGuardNext,
	type RouteLocationNormalized,
} from "vue-router";

const routes: RouteRecordRaw[] = [
	{
		path: "/login",
		name: "login",
		component: () => import("../views/login/index.vue"),
	},
	{
		path: "/home",
		name: "home",
		component: () => import("../views/home/index.vue"),
	},
];

const router = createRouter({
	history: createWebHistory(),
	routes,
});

router.beforeEach(
	(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
		const token = localStorage.getItem("token");
		if (token) {
			// 如果有 token，无论当前要访问的是什么路由，都进入首页
			if (["/", "/login"].includes(to.path)) {
				// 如果当前要访问登录页，重定向到首页
				next("/home");
			} else {
				next();
			}
		} else {
			// 如果没有 token，除了登录页，其他路由都重定向到登录页
			if (to.path !== "/login") {
				next("/login");
			} else {
				next();
			}
		}
	}
);

export default router;
